import Scene from "../Scene";
import { TLayout, TButton, SceneState } from "../SceneControl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SelectScene extends Scene {

    /**
     * 所有是按钮的节点，手动传入
     */
    @property([cc.Node])
    handleNodes: cc.Node[] = [];

    @property(cc.Node)
    backNode: cc.Node = null;

    waitRefresh: boolean;

    protected onEnable(): void {
        super.onEnable();
        this.waitRefresh = false;
        this.handleNodes.forEach(node => {
            this.listenAncestors(node);
        })
        this.initScene()
    }

    protected onDisable(): void {
        super.onDisable();
        this.handleNodes.forEach(node => {
            this.unlistenAncestors(node);
        })
    }

    // 递归监听祖先节点的事件
    private listenAncestors(node: cc.Node) {
        while (node) {
            node.on("active-in-hierarchy-changed", this.onActiveInHierarchyChanged, this);
            node = node.parent;
        }
    }

    // 递归移除祖先节点的事件监听
    private unlistenAncestors(node: cc.Node) {
        while (node) {
            node.off("active-in-hierarchy-changed", this.onActiveInHierarchyChanged, this);
            node = node.parent;
        }
    }

    public initScene() {
        let layout = new TLayout();
        let btns = this.getBtns();
        if (btns.length > 0) {
            layout.buttonList = btns;
        } else {
            layout.buttonList = [[new TButton(this.node)]];
            this.tscene.sceneState = SceneState.hideFinger;
        }

        this.tscene.addLayout(layout);
        this.tscene.onBack = this.backNode;
        this.tscene.joinController();
    }

    getBtns(): TButton[][] {
        let handleNodes = this.handleNodes.filter(item => item.activeInHierarchy);
        return Scene.sortNodesIntoGrid(handleNodes, 150, true) as TButton[][];
    }

    onActiveInHierarchyChanged() {
        if (this.waitRefresh)
            return;
        this.waitRefresh = true;
        this.scheduleOnce(this.refreshBtns, 0.1);
    }

    refreshBtns() {
        this.waitRefresh = false;
        let layout = this.tscene.currLayout;
        let btns = this.getBtns();

        if (btns.length > 0) {
            layout.buttonList = btns;
            this.tscene.sceneState = SceneState.normal;
        } else {
            layout.buttonList = [[new TButton(this.node)]];
            this.tscene.sceneState = SceneState.hideFinger;
        }
        this.tscene.apply();
    }
}
